/**
 * 智能缓存工具
 */
export default class SmartStorageService {
  private static prefixKey?: string = '';
  private static instance: SmartStorageService;

  private constructor() {}

  public static getInstance(prefixKey: string = ''): SmartStorageService {
    if (!this.instance) {
      this.prefixKey = prefixKey;
      this.instance = new SmartStorageService();
    }
    return this.instance;
  }

  private getKey(key: string): string {
    return `${SmartStorageService.prefixKey}.${key}`
  }

  // 设置值
  public setItem(key: string, value: any): void {
    const stringData = JSON.stringify({
      value,
      time: Date.now
    });
    sessionStorage.setItem(this.getKey(key), stringData);
  }

  // 获取值
  public getItem(key: string, def: any = null): any {
    const val = sessionStorage.getItem(this.getKey(key));
    if (!val) {
      // key不存在，则返回默认值
      return def;
    }
    try {
      const data = JSON.parse(val);
      const { value } = data;
      return value;
    } catch (error) {
      console.error('获取缓存发生异常');
      return def;
    }
  }

  // 移除键值对
  public removeItem(key: string): void {
    sessionStorage.removeItem(this.getKey(key));
  }

  // 清除所有键值对
  public clear(): void {
    sessionStorage.clear();
  }
}

export const userStoarge: SmartStorageService = SmartStorageService.getInstance('user');